# -*- coding: utf-8 -*-
import requests
import numpy as np
import cv2
from pybaseutils import file_utils, image_utils, base64_utils

# url = 'http://192.168.68.102:5000/detect'
url = 'http://0.0.0.0:5000/detect'


# http://192.168.68.79:5000/


class MockRequest(object):
    def request(self, params=None):
        r = requests.post(url, json=params)
        return r.json()

    def detect(self, image, vis=False):
        """
        :param image:
        :return:
        """
        params = {"image": image}
        params = base64_utils.serialization(params)
        result = self.request(params)
        result = base64_utils.deserialization(result)
        if vis: image = self.draw_result(image, result)
        return image, result

    def detect_image_dir(self, image_dir, vis=True):
        """
        :param image_dir: directory or image file path
        :param vis:<bool>
        :return:
        """
        image_list = file_utils.get_files_lists(image_dir, postfix=["*.jpg", "*.png"])
        for image_file in image_list:
            print(image_file)
            image = cv2.imread(image_file)
            image, result = self.detect(image, vis=vis)

    def draw_result(self, image, result: dict, vis=True, delay=0):
        """
        :param image: BGR image
        :param boxes:<np.ndarray>: (num_boxes, 4), box=[xmin,ymin,xmax,ymax]
        :param score:<np.ndarray>: (num_boxes,)
        :param label:<np.ndarray>: (num_boxes,)
        :return:
        """
        color = (255, 0, 0)
        boxes = result.get("boxes", [])
        score = result.get("score", [])
        landm = result.get("landm", [])
        segms = result.get("segms", [])
        label = result.get("label", [])
        names = result.get("names", [])
        if not names: names = label
        texts = ["{} {:3.3f}".format(n, s) for n, s in zip(names, score)]
        image = image_utils.draw_image_bboxes_text(image, boxes, texts, color=color, thickness=2,
                                                   fontScale=0.8,  drawType="ch")
        image = image_utils.draw_landmark(image, landm, radius=2, fontScale=1.0, color=color)
        if vis: image_utils.cv_show_image("image", image, delay=delay)
        return image


if __name__ == '__main__':
    image_dir = "dataset/test_image"
    image_dir = "/home/PKing/nasdata/tmp/tmp/RealFakeFace/living/portrait/image/portrait3"
    s = MockRequest()
    s.detect_image_dir(image_dir=image_dir)
